package bar.dark.lee.setting.auto;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import bar.dark.lee.BDConstents;
import bar.dark.lee.IntroActivitiy;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.InsertInActivity;
import bar.dark.lee.insert.InsertOutActivity;
import bar.dark.lee.manager.card.CreditCardAddActivity;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

public class AutoInsertActivity extends SuperActivity
{
	public static final String TODAY_INTRO = "today_intro";
	
	public static final String REQUEST_KEY = "request_key";
	public static final String INSERT_HALBU = "insert_halbu";
	
	public static final int REQUEST_AUTO_DATE = 0;
	public static final int REQUEST_AUTO_CATEGORY = 1;
	public static final int REQUEST_AUTO_BANK = 2;
	public static final int REQUEST_AUTO_CREDIT = 3;
	public static final int REQUEST_AUTO_CREDIT_DATE = 4;
	
	public static final String ALL = "무기한";
	public static final String NO_ALL = "직접입력";
	
	public static final int IN_CATEGORY = 0;
	public static final int OUT_CATEGORY = 1;
	
	private DBSQLite sql;
	
	private View inOutRadioView;
	
	private RadioButton outRadio;
	private RadioButton inRadio;
	
	private View bankCreditRadioView;
	
	private RadioButton bankRadio;
	private RadioButton creditRadio;
	
	private EditText name;
	
	private View dateView;
	private TextView dateText;
	
	private View bankView;
	private TextView bankText;
	
	private View creditView;
	private TextView creditText;
	
	private View categoryView;
	private TextView categoryText;
	
	private EditText money;
	
	private View creditHalBuView;
	private EditText creditHalBuEditText;
	
	private View creditDateView;
	private TextView creditDateTitle;
	private TextView creditDateTextView;
	private View creditDateAllView;
	private EditText creditDateEditText;
	
	private View memoView;
	private EditText memo;
	
	private Button saveButton;
	
	private ArrayList<String> dateList = new ArrayList<String>();
	private ArrayList<String> categoryList;
	private ArrayList<String> bankList;
	private ArrayList<String> creditList;
	private ArrayList<String> creditDateList = new ArrayList<String>();
	
	private Intent intent;
	private int flag;
	private int categoryFlag;
	private AutoData data;
	
	private int autoDateFlag = -1;
	
	private int maxId = -1;
	
	private int handlerFlag = 0;
	private int handlerResultFlag = 0;
	
	private int dialogFlag = 0;
	
	private String insertHalBuFlag = "";
	
	private boolean sosujumFlag = false;
	
	private int toYear;
	private int toMonth;
	private int toDay;
	
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			
			if (BDUtil.getCommaDel(money.getText().toString()).equals(""))
			{
//				dialogFlag = 1;
//				BDUtil.showDialogOK(AutoInsertActivity.this, "확인", "금액을 먼저 입력해주세요.",
//						new DialogInterface.OnClickListener()
//						{
//							@Override
//							public void onClick(DialogInterface dialog, int which)
//							{
//								dialogFlag = 0;
//							}
//						});
				
				creditDateEditText.setVisibility(View.GONE);
				
				if (insertHalBuFlag.equals(INSERT_HALBU))
				{
					creditDateTextView.setText("2");
				}
				else
				{
					creditDateTextView.setText(ALL);
					creditHalBuView.setVisibility(View.GONE);
				}
				
				creditDateAllView.setVisibility(View.VISIBLE);
				return;
			}
			
			sosujumFlag = false;
			
			try
			{
				int checkMoney = Integer.parseInt(BDUtil.getCommaDel(money.getText().toString()));
			} catch (NumberFormatException e)
			{
				sosujumFlag = true;
			}
			
			double tempMoney = Double.parseDouble(BDUtil.getCommaDel(money.getText().toString()));
			
			if (creditDateEditText.getVisibility() == View.VISIBLE)
			{
				if (creditDateEditText.getText().toString().equals(""))
				{
					return;
				}
				
				int count = Integer.parseInt(creditDateEditText.getText().toString());
				
				if ( (tempMoney < count) && (tempMoney > 9) )
				{
					dialogFlag = 1;
					BDUtil.showDialogOK(AutoInsertActivity.this, "확인", "금액을 나눌수가 없습니다. 할부 개월보다 큰 금액을 입력해주세요.",
							new DialogInterface.OnClickListener()
							{
								@Override
								public void onClick(DialogInterface dialog, int which)
								{
									dialogFlag = 0;
								}
							});
					
					creditDateEditText.setVisibility(View.GONE);
					
					if (insertHalBuFlag.equals(INSERT_HALBU))
					{
						creditDateTextView.setText("2");
					}
					else
					{
						creditDateTextView.setText(ALL);
						creditHalBuView.setVisibility(View.GONE);
					}
					
					creditDateAllView.setVisibility(View.VISIBLE);
					return;
				}
				else
				{
					if (sosujumFlag)
					{
						double divMoney = (((double) tempMoney) / ((double) count));
						
						//creditHalBuTextView.setText(BDUtil.getWon(divMoney + "") + shape);
						creditHalBuEditText.setText(BDUtil.getWon(divMoney + ""));
					}
					else
					{
						int divMoney = (int)(((double) tempMoney) / ((double) count));
						
						//creditHalBuTextView.setText(BDUtil.getWon(divMoney + "") + shape);
						creditHalBuEditText.setText(BDUtil.getWon(divMoney + ""));
					}
					
					handlerResultFlag = 1;
				}
			}
			else
			{
				int count = Integer.parseInt(creditDateTextView.getText().toString());
				
				if ( (tempMoney < count) && (tempMoney > 9) )
				{
					dialogFlag = 1;
					BDUtil.showDialogOK(AutoInsertActivity.this, "확인", "금액을 나눌수가 없습니다. 할부 개월보다 큰 금액을 입력해주세요.",
							new DialogInterface.OnClickListener()
							{
								@Override
								public void onClick(DialogInterface dialog, int which)
								{
									dialogFlag = 0;
								}
							});
					
					creditDateEditText.setVisibility(View.GONE);
					
					if (insertHalBuFlag.equals(INSERT_HALBU))
					{
						creditDateTextView.setText("3");
					}
					else
					{
						creditDateTextView.setText(ALL);
						creditHalBuView.setVisibility(View.GONE);
					}
					
					creditDateAllView.setVisibility(View.VISIBLE);
					return;
				}
				else
				{
					if (sosujumFlag)
					{
						double divMoney = (((double) tempMoney) / ((double) count)); 
						
						//creditHalBuTextView.setText(BDUtil.getWon(divMoney + "") + shape);
						creditHalBuEditText.setText(BDUtil.getWon(divMoney + ""));
					}
					else
					{
						int divMoney = (int)(((double) tempMoney) / ((double) count)); 
						
						//creditHalBuTextView.setText(BDUtil.getWon(divMoney + "") + shape);
						creditHalBuEditText.setText(BDUtil.getWon(divMoney + ""));
					}
					
					handlerResultFlag = 1;
				}
			}
		}
	};;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.auto_insert_activity);
		
		intent = getIntent();
		
		flag = intent.getIntExtra(AutoActivity.AUTO_UPDATE_DELECT_FLAG, AutoActivity.AUTO_INSERT);
		
		if (flag == AutoActivity.AUTO_UPDATE)
		{
			setTitle("자동화/할부 수정");
		}
		else
		{
			setTitle("자동화/할부 추가");
		}
		
		Calendar cal = Calendar.getInstance();
		toYear = cal.get(Calendar.YEAR);
		toMonth = cal.get(Calendar.MONTH);
		toDay = cal.get(Calendar.DAY_OF_MONTH);
		
		setFindView();
		setOnClickListener();
		setData();
	}
	
	private void setFindView()
	{
		inOutRadioView = findViewById(R.id.autoInsertInOutRadioView);
		
		outRadio = (RadioButton) findViewById(R.id.autoInsertRadioOut);
		inRadio = (RadioButton) findViewById(R.id.autoInsertRadioIn);
		
		bankCreditRadioView = findViewById(R.id.autoInsertBankCreditRadioView);
		
		bankRadio = (RadioButton) findViewById(R.id.autoInsertRadioBank);
		creditRadio = (RadioButton) findViewById(R.id.autoInsertRadioCredit);
		
		name = (EditText) findViewById(R.id.autoInsertName);
		
		dateView = findViewById(R.id.autoDate);
		dateText = (TextView) findViewById(R.id.autoDateTextView);
		
		bankView = findViewById(R.id.autoBank);
		bankText = (TextView) findViewById(R.id.autoBankTextView);
		
		creditView = findViewById(R.id.autoCredit);
		creditText = (TextView) findViewById(R.id.autoCreditTextView);
		
		categoryView = findViewById(R.id.autoCategory);
		categoryText = (TextView) findViewById(R.id.autoCategoryTextView);
		
		money = (EditText) findViewById(R.id.autoInsertMoney);
		EditTextInputFilter.filteringMoneyEditText(money);
		
		creditHalBuView = findViewById(R.id.autoInsertCreditHalBuMoneyView);
		creditHalBuEditText = (EditText) findViewById(R.id.autoInsertCreditHalBuMoneyTextView);
		EditTextInputFilter.filteringMoneyEditText(creditHalBuEditText);
		
		creditDateView = findViewById(R.id.autoCreditDete);
		creditDateTitle = (TextView) findViewById(R.id.autoCreditDateTitle);
		creditDateTextView = (TextView) findViewById(R.id.autoCreditDateTextView);
		creditDateAllView = findViewById(R.id.autoCreditDateAllView);
		creditDateEditText = (EditText) findViewById(R.id.autoCreditDateEditText);
		EditTextInputFilter.filteringZero(creditDateEditText);
		
		memoView = findViewById(R.id.autoMemoView);
		memo = (EditText) findViewById(R.id.autoMemo);
		
		saveButton = (Button) findViewById(R.id.autoInsertSaveButton);
	}
	
	private void setData()
	{
		insertHalBuFlag = intent.getStringExtra(REQUEST_KEY);
		
		if (insertHalBuFlag == null)
		{
			insertHalBuFlag = "";
		}
		
		if (insertHalBuFlag.equals(INSERT_HALBU))
		{
			inOutRadioView.setVisibility(View.GONE);
			bankRadio.setVisibility(View.GONE);
			creditRadio.setChecked(true);
			
			bankView.setVisibility(View.GONE);
			creditView.setVisibility(View.VISIBLE);
			creditDateView.setVisibility(View.VISIBLE);
			creditHalBuView.setVisibility(View.VISIBLE);
			
			setTitle("할부 추가");
			
			setGoneTipButton();
			
			creditDateList.add(NO_ALL);
			creditDateList.add("2");
			creditDateList.add("3");
			creditDateList.add("4");
			creditDateList.add("5");
			creditDateList.add("6");
			creditDateList.add("10");
			creditDateList.add("12");
			creditDateList.add("24");
			creditDateList.add("36");
			creditDateList.add("48");
		}
		else
		{
			creditDateList.add(ALL);
			creditDateList.add(NO_ALL);
			creditDateList.add("2");
			creditDateList.add("3");
			creditDateList.add("4");
			creditDateList.add("5");
			creditDateList.add("6");
			creditDateList.add("10");
			creditDateList.add("12");
			creditDateList.add("24");
			creditDateList.add("36");
			creditDateList.add("48");
		}
		
		for (int i = 0; i < 30; i++)
		{
			String date = "" + (i + 1);
			dateList.add(date);
		}
		
		setMoneyKindData();
		
		if (flag == AutoActivity.AUTO_INSERT)
		{
			setInsertData();
		}
		else if (flag == AutoActivity.AUTO_UPDATE)
		{
			setUpdateData();
		}
	}

	private void setUpdateData()
	{
		data = intent.getParcelableExtra(AutoSelectActivity.AUTO_SELECT_DATA);
		
		if (data.getMoneytype().equals("1"))
		{
			outRadio.setChecked(true);
			inRadio.setChecked(false);
			setCategoryData(OUT_CATEGORY);
		}
		else
		{
			outRadio.setChecked(false);
			inRadio.setChecked(true);
			setCategoryData(IN_CATEGORY);
		}
		
		if (data.getKind().equals("1"))
		{
			bankRadio.setChecked(true);
			creditRadio.setChecked(false);
			bankView.setVisibility(View.VISIBLE);
			creditView.setVisibility(View.GONE);
			bankText.setText(data.getMoneykind());
			creditDateView.setVisibility(View.GONE);
		}
		else
		{
			bankRadio.setChecked(false);
			creditRadio.setChecked(true);
			bankView.setVisibility(View.GONE);
			creditView.setVisibility(View.VISIBLE);
			creditText.setText(data.getMoneykind());
			creditDateView.setVisibility(View.VISIBLE);
			
			setCreditDateData();
		}
		
		name.setText(data.getName());
		
		String date = data.getSigndate();
		
		if (date.length() < 3)
		{
			dateText.setText(BDUtil.getDate(toYear, toMonth+1, Integer.parseInt(data.getAutodate())));
		}
		else
		{
			int [] dates = BDUtil.getDateSet(date);
			
			Calendar cal = Calendar.getInstance();
			cal.set(dates[0], dates[1], dates[2]);
			cal.add(Calendar.MONTH, 1);
			
			dateText.setText(BDUtil.getDate(
					cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), Integer.parseInt(data.getAutodate())));
		}
		
		categoryText.setText(data.getCategory());
		
		money.setText(data.getMoney());
		
		if (data.getMemo() == null || data.getMemo().equals(""))
		{
			memo.setText("");
		}
		else
		{
			memo.setText(data.getMemo());
		}
	}

	private void setCreditDateData()
	{
		sql.selectMapTile(this, "SELECT * FROM auto_credit_date WHERE linkid ="
				+ data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				AutoCreditDateData dateData = null;
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int monthcountIdx = c.getColumnIndex("monthcount");
				int signcountIdx = c.getColumnIndex("signcount");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					dateData = new AutoCreditDateData();
					
					dateData.setId(c.getInt(idIdx) + "");
					dateData.setName(c.getString(nameIdx));
					dateData.setMonthcount(c.getInt(monthcountIdx) + "");
					dateData.setSigncount(c.getInt(signcountIdx) + "");
					dateData.setLinkid(c.getInt(linkidIdx) + "");
					
					c.moveToNext();
				}
				
				creditDateView.setVisibility(View.VISIBLE);
				creditDateTitle.setText("남은할부개월");
				
				if (dateData == null)
				{
					creditDateEditText.setVisibility(View.GONE);
					creditDateAllView.setVisibility(View.VISIBLE);
					creditDateTextView.setText(creditDateList.get(0));
					autoDateFlag = -1;
				}
				else
				{
					creditDateEditText.setVisibility(View.VISIBLE);
					creditDateAllView.setVisibility(View.GONE);
					creditDateEditText.setText(Integer.parseInt(dateData.getMonthcount()) 
							- Integer.parseInt(dateData.getSigncount()) + "");
					autoDateFlag = 0;		
				}
			}
		});
	}

	private void setInsertData()
	{
		dateText.setText(BDUtil.getDate(toYear, toMonth+1, toDay));
		
		creditDateTitle.setText("할부개월");
		
		if (insertHalBuFlag == null)
		{
			insertHalBuFlag = "";
		}
		
		if (insertHalBuFlag.equals(INSERT_HALBU))
		{
			creditDateTextView.setText(creditDateList.get(1));
			
			String strCardName = intent.getStringExtra(InsertOutActivity.HALBU_CARD_NAME);
			String strDate = intent.getStringExtra(InsertOutActivity.HALBU_DATE);
			String strMoney = intent.getStringExtra(InsertOutActivity.HALBU_MONEY);
			String strMemo = intent.getStringExtra(InsertOutActivity.HALBU_MEMO);
			String strHalbuMonth = intent.getStringExtra(InsertOutActivity.HALBU_MONTH);
			
			if (strCardName == null)
			{
				strCardName = "";
			}
			
			if (strDate == null)
			{
				strDate = "";
			}
			else
			{
				if (strDate.length() > 0)
				{
//					strDate = strDate.substring(6, 8);
					
					try
					{
						int [] dates = BDUtil.getDateSet(strDate);
						
						strDate = BDUtil.getDate(dates[0], dates[1], dates[2]);
					} catch (Exception e)
					{
						strDate = "";
					}
				}
			}
			
			if (strMoney == null)
			{
				strMoney = "";
			}
			
			if (strMemo == null)
			{
				strMemo = "";
			}
			
			if (strHalbuMonth == null)
			{
				strHalbuMonth = "0";
			}
			
			try 
			{
				if (!strDate.equalsIgnoreCase(""))
				{
					dateText.setText(strDate);
				}
				if (!strCardName.equalsIgnoreCase(""))
				{
					creditText.setText(strCardName);
				}
				if (!strMoney.equalsIgnoreCase(""))
				{
					money.setText(strMoney);
				}
				if (!strMemo.equalsIgnoreCase(""))
				{
					memo.setText(strMemo);
				}
				if (!strHalbuMonth.equalsIgnoreCase("0"))
				{
					creditDateTextView.setText(Integer.parseInt(strHalbuMonth)+"");
				}
			} catch (Exception e) {
			}
			
			Toast.makeText(superContext, "문자 불러오기를 통해 입력 중이신 경우에는 내용들을 확인 한 후에 저장을 눌러주세요", Toast.LENGTH_LONG).show();
		}
		else
		{
			creditDateTextView.setText(creditDateList.get(0));
		}
		
		setCategoryData(OUT_CATEGORY);
	}

	private void setMoneyKindData()
	{
		sql.selectMapTile(this, "SELECT name FROM ( " +
				"SELECT b.name name FROM bankbook b, bankbook_detail d " +
				"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
				"UNION ALL " +
				"SELECT name FROM ( " +
				"SELECT b.name name FROM bankbook b, bankbook_detail d " +
				"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				bankList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					bankList.add(kind);
					c.moveToNext();
				}
				
				if (bankList.size() < 1)
				{
					String memo = "없음";
					bankList.add(memo);
					bankView.setClickable(false);
					bankView.setTag(false);
				}
				else
				{
					bankView.setClickable(true);
					bankView.setTag(true);
				}
				
				bankText.setText(bankList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				creditList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					creditList.add(kind);
					c.moveToNext();
				}
				
				if (creditList.size() < 1)
				{
					String memo = "없음";
					creditList.add(memo);
					creditView.setClickable(false);
					creditView.setTag(false);
				}
				else
				{
					creditView.setClickable(true);
					creditView.setTag(true);
				}
				
				creditText.setText(creditList.get(0).toString());
			}
		});
	}
	
	private void setOnClickListener()
	{
		outRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setCategoryData(OUT_CATEGORY);
			}
		});
		
		inRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setCategoryData(IN_CATEGORY);
			}
		});
		
		bankRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				creditView.setVisibility(View.GONE);
				creditDateView.setVisibility(View.GONE);
				
				bankView.setVisibility(View.VISIBLE);
				
				inRadio.setVisibility(View.VISIBLE);
			}
		});
		
		creditRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				bankView.setVisibility(View.GONE);
				
				creditView.setVisibility(View.VISIBLE);
				creditDateView.setVisibility(View.VISIBLE);
				
				inRadio.setVisibility(View.GONE);
				outRadio.setChecked(true);
				inRadio.setChecked(false);
			}
		});
		
		dateView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
//				Intent intent = new Intent(AutoInsertActivity.this, RadioDialogActivity.class);
//				intent.putExtra(RadioDialogActivity.RADIODATA, dateList);
//				intent.putExtra(RadioDialogActivity.RADIOSELECT, dateText.getText().toString());
//				startActivityForResult(intent, REQUEST_AUTO_DATE);
				
				CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
					@Override
					public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
						
						dateText.setText(BDUtil.getDate(year, monthOfYear+1, dayOfMonth));
				    	
						toYear = year;
						toMonth = monthOfYear;
						toDay = dayOfMonth;
					}
				}, toYear, toMonth, toDay);
				
				cpd.show();
			}
		});
		
		categoryView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(AutoInsertActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, categoryList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, categoryText.getText().toString());
				
				if (categoryFlag == OUT_CATEGORY)
				{
					intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_OUT_TYPE);
					intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_OUT_TYPE_STRING);
				}
				else if (categoryFlag == IN_CATEGORY)
				{
					intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_IN_TYPE);
					intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_IN_TYPE_STRING);
				}
				
				startActivityForResult(intent, REQUEST_AUTO_CATEGORY);
			}
		});
		
		bankView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(AutoInsertActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, bankList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, bankText.getText().toString());
				startActivityForResult(intent, REQUEST_AUTO_BANK);
			}
		});
		
		creditView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(AutoInsertActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, creditList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, creditText.getText().toString());
				startActivityForResult(intent, REQUEST_AUTO_CREDIT);
			}
		});
		
		creditDateView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(AutoInsertActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, creditDateList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, creditDateTextView.getText().toString());
				startActivityForResult(intent, REQUEST_AUTO_CREDIT_DATE);
			}
		});
		
		money.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
				if (creditHalBuView.getVisibility() == View.VISIBLE && dialogFlag == 0)
				{
					handlerFlag = 1;
					handlerResultFlag = 0;
					//creditHalBuEditText.setText("계산중...");
					handler.sendMessage(new Message());
				}
			}
			
			@Override
			public void afterTextChanged(Editable s)
			{
			}
		});
		
		creditDateEditText.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
				if (creditHalBuView.getVisibility() == View.VISIBLE && dialogFlag == 0)
				{
					handlerFlag = 1;
					handlerResultFlag = 0;
					//creditHalBuEditText.setText("계산중...");
					handler.sendMessage(new Message());
				}
			}
			
			@Override
			public void afterTextChanged(Editable s)
			{
			}
		});
		
		saveButton.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				if (creditHalBuView.getVisibility() == View.VISIBLE)
				{
					if ( creditHalBuEditText.getText().toString().equals("0 원") || creditHalBuEditText.getText().toString().equals("") ) 
					{
						BDUtil.showDialogOK(AutoInsertActivity.this, "확인", "할부 개월보다 큰 금액을 입력해주세요.",
						new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								money.setText("");
							}
						});
						return;
					}
				}
				
				if (flag == AutoActivity.AUTO_INSERT)
				{
					setAutoInsertData();
				}
				else if (flag == AutoActivity.AUTO_UPDATE)
				{
					setAutoUpdateData();
				}
			}
		});
	}
	
	/**
	 * 0번은 in 1번은 out
	 * @param flag
	 */
	private void setCategoryData(int flag)
	{
		String table = "";
		
		if (flag == IN_CATEGORY)
		{
			table = "category_in_list";
			categoryFlag = IN_CATEGORY;
		}
		else if (flag == OUT_CATEGORY)
		{
			table = "category_out_list";
			categoryFlag = OUT_CATEGORY;
		}
		
		if (table.equals(""))
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT kind FROM " + table + " ORDER BY count DESC", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				categoryList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("kind");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					categoryList.add(kind);
					c.moveToNext();
				}
				
				if (categoryList.size() < 1)
				{
					String memo = "없음";
					categoryList.add(memo);
					categoryView.setClickable(false);
				}
				else
				{
					categoryView.setClickable(true);
				}
				
				categoryText.setText(categoryList.get(0).toString());
			}
		});
	}
	
	private void setAutoUpdateData()
	{
		if (data == null)
		{
			return;
		}
		
		if (BDUtil.getCommaDel(money.getText().toString()).equals(""))
		{
			BDUtil.showDialog(this, "경고", "금액을 입력해주세요.");
			return;
		}
		
		if (name.getText().toString().equals(""))
		{
			BDUtil.showDialog(this, "경고", "이체이름을 입력해주세요.");
			return;
		}
		
		if (bankRadio.isChecked())
		{
			if ((Boolean) bankView.getTag() == false)
			{
				BDUtil.showDialogManager(superContext, "통장이 하나도 없습니다.");
				return;
			}
		}
		else if (creditRadio.isChecked())
		{
			if ((Boolean) creditView.getTag() == false)
			{
				BDUtil.showDialogManager(superContext, "신용카드가 하나도 없습니다.");
				return;
			}
			
			if (handlerFlag != 0)
			{
				if (handlerResultFlag == 0)
				{
					BDUtil.showDialog(this, "경고", "할부 금액이 계산되지 않았습니다. 다시 선택해주세요.");
					return;
				}
			}
		}
		
		new ShowDialog().execute(BDUtil.asyncFlag, 2);
	}

	private void setUpdate()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		if (outRadio.isChecked())
		{
			map.put("moneytype", "1");
		}
		else if (inRadio.isChecked())
		{
			map.put("moneytype", "2");
		}
		
		if (bankRadio.isChecked())
		{
			map.put("kind", "1");
			map.put("moneykind", bankText.getText().toString());
		}
		else if (creditRadio.isChecked())
		{
			map.put("kind", "2");
			map.put("moneykind", creditText.getText().toString());
		}
		
		map.put("name", name.getText().toString());
		map.put("category", categoryText.getText().toString());
		
//		map.put("autodate", dateText.getText().toString());
		map.put("autodate", toDay + "");
		
//		Calendar cal = Calendar.getInstance();
//		int year = cal.get(Calendar.YEAR);
//		int month = cal.get(Calendar.MONTH)+1;
//		int day = Integer.parseInt(dateText.getText().toString());
		
		Calendar cal = Calendar.getInstance();
		cal.set(toYear, toMonth, toDay);
		cal.add(Calendar.MONTH, -1);
		
		map.put("signdate", BDUtil.getDateDB(
				cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH)));
		
		map.put("money", BDUtil.getCommaDel(money.getText().toString()));
		
		map.put("memo", memo.getText().toString());
		
		String [] whereArgs = new String[]{data.getId()};
		sql.update(this, "auto_bank", map, "id = ?", whereArgs);
		
		if (creditRadio.isChecked())
		{
			if (autoDateFlag > -1)
			{
				if (!creditDateTextView.getText().toString().equals(ALL) 
						|| creditDateEditText.getVisibility() == View.VISIBLE)
				{
					setUpdateCreditDateData();
				}
				else
				{
					String [] where = new String[]{data.getId() + ""};
					sql.delete(this, "auto_credit_date", "id = ?", where);
				}
			}
			else
			{
				if (!creditDateTextView.getText().toString().equals(ALL)
						|| creditDateEditText.getVisibility() == View.VISIBLE)
				{
					setInsertCreditDateData(1, false);
				}
			}
		}
	}
	
	private void setAutoInsertData()
	{
		if (BDUtil.getCommaDel(money.getText().toString()).equals(""))
		{
			BDUtil.showDialog(this, "경고", "금액을 입력해주세요.");
			return;
		}
		
		if (name.getText().toString().equals(""))
		{
			BDUtil.showDialog(this, "경고", "이체이름을 입력해주세요.");
			return;
		}
		
		if (categoryText.getText().toString().equals("없음"))
		{
			BDUtil.showDialog(this, "경고", "카테고리가 없습니다. 카테고리 셋팅에 가셔서 카테고리를 추가해주세요.");
			return;
		}
		
		if (bankRadio.isChecked())
		{
			if ((Boolean) bankView.getTag() == false)
			{
				BDUtil.showDialogManager(superContext, "통장이 하나도 없습니다.");
				return;
			}
		}
		else if (creditRadio.isChecked())
		{
			if ((Boolean) creditView.getTag() == false)
			{
				BDUtil.showDialogManager(superContext, "신용카드가 하나도 없습니다.");
				return;
			}
			
			if (handlerFlag != 0)
			{
				if (handlerResultFlag == 0)
				{
					BDUtil.showDialog(this, "경고", "할부 금액이 계산되지 않았습니다. 다시 선택해주세요.");
					return;
				}
			}
		}
		
		if (insertHalBuFlag.equals(INSERT_HALBU))
		{
			BDUtil.showSelectDialog(this, "알림", 
					"할부를 추가 할 경우 \n통장/신용카드 자동화 설정 값이 '자동'으로 변경됩니다. 할부를 추가 하시겠습니까?", 
					new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
					int autoSetting = pref.getInt(BDConstents.AUTO_SETTING, 0);
					
					if (autoSetting == 0)
					{
						SharedPreferences.Editor editor = pref.edit();
						editor.putInt(BDConstents.AUTO_SETTING, 1);
						editor.commit();
					}
					
					new ShowDialog().execute(BDUtil.asyncFlag, 1);
				}
			}, new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					dialog.dismiss();
				}
			});
		}
		else
		{
			new ShowDialog().execute(BDUtil.asyncFlag, 1);
		}
		
	}

	/**
	 * 데이터를 추가한다.
	 */
	private void setInsert()
	{
		HashMap<String, String> map	= new HashMap<String, String>();
		
		if (bankRadio.isChecked())
		{
			map.put("kind", "" + 1);
			map.put("moneykind", bankText.getText().toString());
		}
		else if (creditRadio.isChecked())
		{
			map.put("kind", "" + 2);
			map.put("moneykind", creditText.getText().toString());
		}
		
		if (outRadio.isChecked())
		{
			map.put("moneytype", "" + 1);
		}
		else if (inRadio.isChecked())
		{
			map.put("moneytype", "" + 2);
		}
		
		map.put("name", name.getText().toString());
//		map.put("autodate", dateText.getText().toString());
		map.put("autodate", toDay + "");
		
//		Calendar cal = Calendar.getInstance();
//		
//		int year = cal.get(Calendar.YEAR);
//		
//		// 이줄은 테스트때문에 넣음.
////		int month = cal.get(Calendar.MONTH)-1;
//		
//		int month = cal.get(Calendar.MONTH)+1;
//		int day = Integer.parseInt(dateText.getText().toString());
//		
//		boolean nowInsertFlag = true;
//		
//		if (!creditDateTextView.getText().toString().equals(ALL)
//				|| creditDateEditText.getVisibility() == View.VISIBLE)
//		{
//			if (day > cal.get(Calendar.DAY_OF_MONTH))
//			{
//				if (month == 1)
//				{
//					year--;
//					month = 12;
//				}
//				else 
//				{
//					month--;
//				}
//			}
//		}
//		else if (day >= cal.get(Calendar.DAY_OF_MONTH))
//		{
//			if (month == 1)
//			{
//				year--;
//				month = 12;
//			}
//			else 
//			{
//				month--;
//			}
//		}
		
		Calendar cal = Calendar.getInstance();
		cal.set(toYear, toMonth, toDay);
		cal.add(Calendar.MONTH, -1);
		
		map.put("signdate", BDUtil.getDateDB(
				cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH)));
		
		map.put("category", categoryText.getText().toString());
		
		if (creditRadio.isChecked())
		{
			if (!creditDateTextView.getText().toString().equals(ALL)
					|| creditDateEditText.getVisibility() == View.VISIBLE)
			{
//				String tempMoney = creditHalBuTextView.getText().toString().replace(" 원", "");
//				tempMoney = tempMoney.replace(",", "");
				map.put("money", BDUtil.getCommaDel(creditHalBuEditText.getText().toString()));
			}
			else
			{
				map.put("money", BDUtil.getCommaDel(money.getText().toString()));
			}
		}
		else
		{
			map.put("money", BDUtil.getCommaDel(money.getText().toString()));
		}
		
		map.put("memo", memo.getText().toString());
		
		sql.insert(this, map, "auto_bank");
		
		if (creditRadio.isChecked())
		{
			if (!creditDateTextView.getText().toString().equals(ALL)
					|| creditDateEditText.getVisibility() == View.VISIBLE)
			{
//				setInsertCreditDateData(0, nowInsertFlag);
				setInsertCreditDateData(0, false);
			}
		}
	}
	
	/**
	 * flag = 1 수정
	 * flag = 0 추가
	 * @param nowInsertFlag 
	 */
	private void setInsertCreditDateData(int flag, boolean nowInsertFlag)
	{
		HashMap<String, String> map	= new HashMap<String, String>();
		
		map.put("name", creditText.getText().toString());
		if (creditDateAllView.getVisibility() == View.VISIBLE)
		{
			map.put("monthcount", creditDateTextView.getText().toString());
		}
		else
		{
			map.put("monthcount", creditDateEditText.getText().toString());
		}
		
		if (flag == 0)
		{
			sql.selectMapTile(this, "SELECT max(id) maxid FROM auto_bank;", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int maxIdIdx = c.getColumnIndex("maxid");
					
					c.moveToFirst();
					
					for (int i = 0; i < c.getCount(); i++)
					{
						maxId = c.getInt(maxIdIdx);
						c.moveToNext();
					}
				}
			});
			
			map.put("linkid", maxId + "");
		}
		else
		{
			map.put("linkid", data.getId());
		}
		
		sql.insert(this, map, "auto_credit_date");
		
//		if (nowInsertFlag)
//		{
//			setCreditOutData(maxId);
//		}
	}
	
	private AutoCreditDateData dateData = null;
	private AutoData tempData = null;
	/**
	 * 할부 일 경우 날짜에 따라서 한번 넣어준다.
	 * @param id
	 */
	private void setCreditOutData(int id)
	{
		sql.selectMapTile(this, "SELECT * FROM auto_bank WHERE id = "
				+ id + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int categoryIdx = c.getColumnIndex("category");
				int moneyIdx = c.getColumnIndex("money");
				int moneytypeIdx = c.getColumnIndex("moneytype");
				int autodateIdx = c.getColumnIndex("autodate");
				int signdateIdx = c.getColumnIndex("signdate");
				int moneykindIdx = c.getColumnIndex("moneykind");
				int memoIdx = c.getColumnIndex("memo");
				int kindIdx = c.getColumnIndex("kind");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					tempData = new AutoData();
					
					tempData.setId(c.getInt(idIdx) + "");
					tempData.setName(c.getString(nameIdx));
					tempData.setCategory(c.getString(categoryIdx));
					tempData.setMoney(c.getString(moneyIdx));
					tempData.setMoneytype(c.getInt(moneytypeIdx) + "");
					tempData.setAutodate(c.getInt(autodateIdx)+ "");
					tempData.setSigndate(c.getInt(signdateIdx)+ "");
					tempData.setMoneykind(c.getString(moneykindIdx));
					tempData.setMemo(c.getString(memoIdx));
					tempData.setKind(c.getInt(kindIdx) + "");
					
					c.moveToNext();
				}
			}
		});
		
		if (tempData == null)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT * FROM auto_credit_date WHERE linkid ="
				+ tempData.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				dateData = null;
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int monthcountIdx = c.getColumnIndex("monthcount");
				int signcountIdx = c.getColumnIndex("signcount");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					dateData = new AutoCreditDateData();
					
					dateData.setId(c.getInt(idIdx) + "");
					dateData.setName(c.getString(nameIdx));
					dateData.setMonthcount(c.getInt(monthcountIdx) + "");
					dateData.setSigncount(c.getInt(signcountIdx) + "");
					dateData.setLinkid(c.getInt(linkidIdx) + "");
					
					c.moveToNext();
				}
			}
		});
		
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("category", tempData.getCategory());
		
		String memo = tempData.getName();
		
		memo = memo + " " + dateData.getMonthcount() + "개월 할부중 1회차";
		
		if (tempData.getMemo() != null)
		{
			memo = memo + " " + tempData.getMemo();
		}
		
		map.put("memo", memo);
		
		map.put("type", BDConstents.CREDIT_TYPE);
		map.put("postmoney", tempData.getMoney());
		
		map.put("moneykind", tempData.getMoneykind());
		
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;
		int day = Integer.parseInt(tempData.getAutodate());
		
		if (day > cal.get(Calendar.DAY_OF_MONTH))
		{
			if (month == 1)
			{
				year--;
				month = 12;
			}
			else
			{
				month--;
			}
		}
		
		map.put("date", BDUtil.getDateDB(year, month, day));
		
		sql.insert(this, map, "in_out");
		
		sql.selectMapTile(this, "SELECT id, outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(tempData.getMoneykind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
//				int money = 0;
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("outmoney");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
					c.moveToNext();
				}
				
//				money = money + Integer.parseInt(data.getMoney());
				money = money.add(new BigDecimal(tempData.getMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("outmoney", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				sql.update(AutoInsertActivity.this, "credit_card", map, "id = ?", whereArgs);
			}
		});
		
		if (dateData != null)
		{
			HashMap<String, String> map1 = new HashMap<String, String>();
			
			int count = Integer.parseInt(dateData.getSigncount()) + 1;
			
			map1.put("signcount", count + "");
			
			String [] whereArgs = new String[]{dateData.getId()};
			sql.update(AutoInsertActivity.this, "auto_credit_date", map1
					, "id = ?", whereArgs);
		}
	}
	
	private void setUpdateCreditDateData()
	{
		HashMap<String, String> map	= new HashMap<String, String>();
		
		map.put("name", creditText.getText().toString());
		if (creditDateAllView.getVisibility() == View.VISIBLE)
		{
			map.put("monthcount", creditDateTextView.getText().toString());
		}
		else
		{
			map.put("monthcount", creditDateEditText.getText().toString());
		}
		
		sql.selectMapTile(this, "SELECT max(id) maxid FROM auto_bank;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int maxIdIdx = c.getColumnIndex("maxid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					maxId = c.getInt(maxIdIdx);
					c.moveToNext();
				}
			}
		});
		
		map.put("linkid", maxId + "");
		
		sql.insert(this, map, "auto_credit_date");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		
		if (resultCode == Activity.RESULT_OK)
		{
//			if (requestCode == REQUEST_AUTO_DATE)
//			{
//				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
//				dateText.setText(selectData);
//			}
			if (requestCode == REQUEST_AUTO_CATEGORY)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				categoryText.setText(selectData);
			}
			else if (requestCode == REQUEST_AUTO_BANK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				bankText.setText(selectData);
			}
			else if (requestCode == REQUEST_AUTO_CREDIT)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				creditText.setText(selectData);
			}
			else if (requestCode == REQUEST_AUTO_CREDIT_DATE)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				
				if (selectData.equals(NO_ALL))
				{
					creditDateAllView.setVisibility(View.GONE);
					creditDateEditText.setVisibility(View.VISIBLE);
					creditHalBuView.setVisibility(View.VISIBLE);
				}
				else
				{
					creditDateAllView.setVisibility(View.VISIBLE);
					creditDateEditText.setVisibility(View.GONE);
					creditDateTextView.setText(selectData);
					
					if (!selectData.equals(creditDateList.get(0)) && !selectData.equals(NO_ALL))
					{
						handlerFlag = 1;
						handlerResultFlag = 0;
						creditHalBuView.setVisibility(View.VISIBLE);
						//creditHalBuEditText.setText("계산중...");
						
						handler.sendMessage(new Message());
					}
					else
					{
						creditHalBuView.setVisibility(View.GONE);
					}
				}
			}
		}
		else if (resultCode == RadioDialogActivity.REFRESH_CATEGORY)
		{
			if (requestCode == REQUEST_AUTO_CATEGORY)
			{
				if (categoryFlag == OUT_CATEGORY)
				{
					final String beforeCategory = categoryText.getText().toString();
					
					sql.selectMapTile(this, "SELECT kind FROM category_out_list ORDER BY count DESC", new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							categoryList = new ArrayList<String>();
							
							int nameIndex = c.getColumnIndex("kind");
							c.moveToFirst();
							
							for (int i = 0; i < c.getCount(); i++)
							{
								String kind = c.getString(nameIndex);
								categoryList.add(kind);
								c.moveToNext();
							}
							
							if (categoryList.size() < 1)
							{
								String memo = "없음";
								categoryList.add(memo);
								categoryView.setClickable(false);
							}
							
							categoryText.setText(beforeCategory);
						}
					});
				}
				else if (categoryFlag == IN_CATEGORY)
				{
					final String beforeCategory = categoryText.getText().toString();
					
					sql.selectMapTile(this, "SELECT kind FROM category_in_list ORDER BY count DESC", new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							categoryList = new ArrayList<String>();
							
							int nameIndex = c.getColumnIndex("kind");
							c.moveToFirst();
							
							for (int i = 0; i < c.getCount(); i++)
							{
								String kind = c.getString(nameIndex);
								categoryList.add(kind);
								c.moveToNext();
							}
							
							if (categoryList.size() < 1)
							{
								String memo = "없음";
								categoryList.add(memo);
								categoryView.setClickable(false);
							}
							
							categoryText.setText(beforeCategory);
						}
					});
				}
			}
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(AutoInsertActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 1)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setInsert();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				else if (arg0[1] == 2)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setUpdate();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				return arg0[0];
			} else 
				return arg0[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				if (insertHalBuFlag.equals(INSERT_HALBU))
				{
					BDUtil.showDialogOK(superContext, "알림", 
							"할부가 추가 되었습니다. 추가 하기 위해 초기 화면으로 이동 됩니다.", new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							BDUtil.btnEnable = true;
							BDUtil.asyncFlag = 0;
							
							Intent intent = new Intent(superContext, IntroActivitiy.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
							startActivity(intent);
						}
					});
				}
				else
				{
					Intent intent = new Intent();
					intent.putExtra(AutoInsertActivity.TODAY_INTRO, true);
					setResult(Activity.RESULT_OK, intent);
					
					BDUtil.showDialogFinish(AutoInsertActivity.this, "알림", "자동이체 추가에 성공하였습니다.");
				}
			}
			else if (result == 2)
			{
				BDUtil.showDialogFinish(AutoInsertActivity.this, "알림", "자동이체 수정에 성공하였습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(AutoInsertActivity.this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_AUTOBANK);
		startActivity(intent);
	}
}
